package com.chenfan.magic.utils;

import javax.servlet.http.HttpServletRequest;

/**
 * 仿注入
 *
 * @author 周夕
 * @date 2020-03-17 20:53
 */
public class AntiSqlInjectionKit {

    //	public final static String regex = "#|/*|*/|'|%|--|and|or|not|use|insert|delete|update|select|count|group|union"
//			+ "|create|drop|truncate|alter|grant|execute|exec|xp_cmdshell|call|declare|source|sql";

    public final static String REGEX = "\\b((?i)'|and|exec|execute|insert|select|delete|update|count|drop|\\*|%|chr|mid|master|truncate|" +
            "char|declare|sitename|net user|xp_cmdshell|;|or|-|\\+|,|like'|and|exec|execute|insert|create|drop|" +
            "table|from|grant|use|group_concat|column_name|" +
            "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|\\*|" +
            "chr|mid|master|truncate|char|declare|or|;|-|--|\\+|,|like|//|/|%|#)\\b";

    /**
     * 把SQL关键字替换为空字符串
     *
     * @param param
     * @return
     */
    public static String filter(String param) {
        if (param == null) {
            return param;
        }
        return param.replaceAll(REGEX, "");
    }

    /**
     * 返回经过防注入处理的字符串
     *
     * @param request
     * @param name
     * @return
     */
    public static String getParameter(HttpServletRequest request, String name) {
        return AntiSqlInjectionKit.filter(request.getParameter(name));
    }

    public static void main(String[] args) {
        String str = "sElect * from test where id = 1 And name != 'sql' ";
        String outStr = "";
        for (int i = 0; i < 1000; i++) {
            outStr = AntiSqlInjectionKit.filter(str);
        }
        System.out.println(outStr);
    }
}
